<template>
  <div>
    <div>
      <el-row>
        <el-col :span="12">
          <el-page-header @back="goBack" :content="articleTitle"></el-page-header>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button v-show="isUpdateArticle" icon="el-icon-delete" class="ml-5" type="danger" @click="deleteArticle">
            删除
          </el-button>
          <el-button v-show="isUpdateArticle" icon="el-icon-edit" class="ml-5" type="primary" @click="startEdit">编辑
          </el-button>
          <el-button v-show="!isUpdateArticle" icon="el-icon-close" class="ml-5" type="warning" @click="cancelEdit">
            取消
          </el-button>
          <el-button v-show="!isUpdateArticle" icon="el-icon-check" class="ml-5" type="success" @click="updateArticle">
            确认修改
          </el-button>
        </el-col>
      </el-row>
    </div>
    <!--        展示详情-->
    <div v-show="isUpdateArticle">
      <el-row :gutter="20" style="margin: 5px 0px;">
        <el-col :span="20" :offset="2">
          <!--                    标题-->
          <p style="text-align: center;font-family: '微软雅黑';font-size: 32px;padding: 40px 0px">{{ articleTitle }}</p>
          <!--                    时间-->
          <el-row style="font-family: '微软雅黑';font-size: 12px;padding-bottom: 10px">
            <el-col :span="12"><p style="text-align: left">创建时间：{{ createDatetime }}</p></el-col>
            <el-col :span="12"><p style="text-align: right">修改时间：{{ updateDatetime }}</p></el-col>
          </el-row>
          <!--                    浏览次数-->
          <p style="font-family: '微软雅黑';font-size: 12px;padding-bottom: 50px;text-align: right">
            浏览量：{{ articleCheckQuantity }}
          </p>
          <!--                    图片-->
          <p style="padding: 30px 0px;text-align: center;">
            <img style="width: 600px;margin: 0px auto" v-if="showCover != null && showCover != '' " :src="showCover"
                 class="image">
          </p>
          <!--                    内容-->
          <p style="font-family: '微软雅黑';" v-html="articleContent"></p>
          <!--                    关联产品-->
          <div style="padding: 20px">
            <el-row :gutter="20">

              <div class="item" v-for="item in correlateProductList" @click="goto(item.productBar)">
                <div style="display: flex">
                  <div>
                    <img v-if="item.productCover != null" :src="$ysyApi+item.productCover" class="image item_image">
                    <img v-if="item.productCover == null" src="../../assets/imageNull.png" class="image item_image">
                  </div>
                  <div class="item_product_content">
                    <div class="item_product_title">
                      {{ item.productCategoryName }}
                    </div>
                    <div class="item_product_intro">
                      {{ item.productIntro }}
                    </div>
                  </div>
                </div>
                <div>
                  <a :href="`/product/productDetails?productBar=${item.productBar}`"
                     style="line-height: 100px;padding: 5px 10px;color: #409eff;text-decoration: none">详情>>></a>
                </div>
              </div>

            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--        修改页面-->
    <div v-show="!isUpdateArticle" style="margin: 5px 0px">
      <el-form ref="form" :model="updateInfo" :rules="rules" label-width="100px" class="demo-ruleForm">
        <!--                文章编号-->
        <el-form-item label="文章编号" prop="articleId">
          <el-input
              type="number"
              placeholder="请输入文章编号"
              v-model="updateInfo.articleId"
              :disabled="true"
              clearable>
          </el-input>
        </el-form-item>
        <!--                文章标题-->
        <el-form-item label="文章标题" prop="articleTitle">
          <el-input
              placeholder="请输入文章标题"
              v-model="updateInfo.articleTitle"
              clearable>
          </el-input>
        </el-form-item>
        <!--                文章简介-->
        <el-form-item label="文章简介" prop="articleIntro">
          <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8}"
              placeholder="请输入内容"
              maxlength="200"
              show-word-limit
              v-model="updateInfo.articleIntro">
          </el-input>
        </el-form-item>
        <!--                文章类别-->
        <el-form-item label="文章类别" prop="articleCategory">
          <el-select class="ml-5" filterable clearable v-for="item in sysCategoryList "
                     v-model="updateInfo.articleCategory" placeholder="消息类型">
            <el-option :label="item.sysCategoryName" :value="item.sysCategoryId"></el-option>
          </el-select>
        </el-form-item>
        <!--                文章封面-->
        <el-form-item label="文章封面">
          <el-upload
              class="avatar-uploader"
              :action="`${$ysyApi}/api/UpLoadFile/`"
              :headers="headers"
              name="file"
              :show-file-list="false"
              :on-success="uploadArticleCover"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <!--                关联产品-->
        <el-form-item label="关联产品" prop="correlateProducts">
          <el-input
              placeholder="请输入关联产品"
              v-model="updateInfo.correlateProducts"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="html">
          <div style="border: 1px solid #ccc;">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                     :mode="mode"/>
            <Editor style="height: 800px; overflow-y: hidden;" v-model="updateInfo.articleContent"
                    :defaultConfig="editorConfig" :mode="mode"
                    @onCreated="onCreated"/>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style src="../../../node_modules/@wangeditor/editor/dist/css/style.css"></style>

<script>
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

export default {
  name: "ArticleDetails",
  components: {Editor, Toolbar},
  data() {
    return {
      loginStatus: true,
      isUpdateArticle: true,
      //图片上传请求头
      headers: {
        Authorization: ''
      },
      articleId: '',//消息编号
      articleTitle: '',//消息标题
      articleContent: '',//消息内容
      articleCover: '',//消息封面
      showCover: '',
      nickname: '',//发布者
      sysCategoryName: '',//消息类别
      articleIntro: '',//消息简介
      articleCheckQuantity: '',//浏览次数
      correlateProducts: '',//关联产品
      createDatetime: '',//发布时间
      updateDatetime: '',//修改时间
      correlateProductList: [],//解析后的关联产品信息
      updateInfo: {
        articleId: '',//消息编号
        articleTitle: '',//消息标题
        articleContent: '',//消息内容
        articleCover: '',//消息封面
        articleCategory: '',//消息类别
        articleIntro: '',//消息简介
        correlateProducts: '',//关联产品
      },
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      sysCategoryList: [],
      editor: null,
      toolbarConfig: {},
      editorConfig: {placeholder: '请输入内容...'},
      mode: 'default', // or 'simple'
      rules: {
        articleTitle: [{required: true, message: '请输入消息标题'}],
        articleContent: [{required: true, message: '请输入消息内容'}],
        articleIntro: [{required: true, message: '请输入消息简介'}],
        articleCategory: [{required: true, message: '请选择消息类别'}],
      }
    }
  },
  created() {
    this.articleId = this.$route.query.articleId
    this.load()
    this.getSysCategoryAll()
    this.headers.Authorization = JSON.parse(localStorage.getItem('user')).token
  },
  methods: {
    // 初始化富文本编辑器
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 返回上一页
    goBack() {
      this.$router.back()
    },
    //上传封面图片
    uploadArticleCover(response, file, fileList) {
      this.imageUrl = this.$ysyApi + response.message
      this.updateInfo.articleCover = response.message
    },
    //判断上传文件是否为jpeg/png图片
    beforeAvatarUpload(file) {
      let isJPG = false;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        isJPG = true;
      }
      if (!isJPG) {
        this.$message.error('上传只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 初始化加载消息详情
    load() {
      this.$axios({
        url: this.$api.FindArticleDetails,
        method: 'get',
        params: {
          articleId: this.articleId
        }
      }).then(res => {
        this.articleId = res.data.articleId//消息编号
        this.articleTitle = res.data.articleTitle//消息标题
        this.articleContent = res.data.articleContent//消息内容
        if (res.data.articleCover != '') {
          this.articleCover = res.data.articleCover//消息封面
          this.showCover = this.$ysyApi + res.data.articleCover//消息封面
        }
        this.nickname = res.data.nickname//发布者
        this.sysCategoryName = res.data.sysCategoryName//消息类别
        this.articleIntro = res.data.articleIntro//消息简介
        this.articleCheckQuantity = res.data.articleCheckQuantity//浏览次数
        this.correlateProducts = res.data.correlateProducts//关联产品
        this.createDatetime = res.data.createDatetime//发布时间
        this.updateDatetime = res.data.updateDatetime//修改时间
        if (this.correlateProducts != '') {
          let productBarList = this.correlateProducts.split(',')
          for (let i = 0; i < productBarList.length; i++) {
            this.getCorrelateProduct(productBarList[i]);
          }
        }
      })
    },
    // 获取所有消息类别
    getSysCategoryAll() {
      this.$axios({
        url: this.$api.FindSysCategoryAll,
        method: 'get',
        params: {
          sysCategoryScopeAction: '消息'
        }
      }).then(res => {
        this.sysCategoryList = res.data
      })
    },
    // 获取关联商品的详情
    getCorrelateProduct(productBar) {
      this.$axios({
        url: this.$api.GetProductDetails,
        method: 'get',
        params: {
          ProductBar: productBar
        }
      }).then(res => {
        this.correlateProductList.push(res.data)
      })
    },
    //删除消息
    deleteArticle() {
      this.$confirm('此操作将删除该消息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'delete',
          url: this.$api.DeleteArticle,
          headers: {'content-type': 'multipart/form-data'},
          data: {
            'articleId': this.articleId
          }
        }).then(res => {
          if (res.code === 200 || res.code == false) {
            this.$notify({
              title: '成功',
              message: '消息删除成功',
              type: 'success'
            });
            this.goBack()
          } else {
            this.$notify({
              title: '失败',
              message: res.msg,
              type: 'error'
            });
            this.load()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //开始编辑
    startEdit() {
      this.isUpdateArticle = false
      this.updateInfo.articleId = this.articleId//消息编号
      this.updateInfo.articleTitle = this.articleTitle//消息标题
      this.updateInfo.articleContent = this.articleContent//消息内容
      this.updateInfo.articleCover = this.articleCover//消息封面
      this.updateInfo.articleIntro = this.articleIntro//消息简介
      this.updateInfo.correlateProducts = this.correlateProducts//关联产品
    },
    //取消编辑
    cancelEdit() {
      this.isUpdateArticle = true
      this.updateInfo.articleId = ''//消息编号
      this.updateInfo.articleTitle = ''//消息标题
      this.updateInfo.articleContent = ''//消息内容
      this.updateInfo.articleCover = ''//消息封面
      this.updateInfo.articleCategory = ''//消息类别
      this.updateInfo.articleIntro = ''//消息简介
      this.updateInfo.correlateProducts = ''//关联产品
    },
    //开始修改
    updateArticle() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //通过验证
          this.$axios({
            url: this.$api.InsertArticle,
            method: 'post',
            headers: {'content-type': 'multipart/form-data'},
            data: this.updateInfo
          }).then(res => {
            this.isUpdateArticle = true
            this.$notify({
              title: '成功',
              message: '消息修改成功',
              type: 'success'
            });
            this.load()
          })
        } else {
          //未通过验证
          alert('请填写完整')
          return false;
        }
      });
    },
    // 点击商品跳转到商品详情
    goto(productBar) {
      this.$router.push({
        path: "/product/productDetails",
        query: {
          productBar: productBar
        }
      })
    }
  }
}
</script>

<style>
.item {
  height: 100px;
  border-radius: 15px;
  margin: 10px 0px;
  box-shadow: 0px 0px 3px 3px #e2e2e2;
  display: flex;
  justify-content: space-between;
}

.item_image {
  height: 100px;
  border-radius: 10px
}

.item_product_content {
  display: flex;
  margin: 5px;
  flex-flow: column;
  justify-content: space-around;
}

.item_product_title {
  font-size: 24px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.item_product_intro {
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>